<script lang="ts" setup>
import { reactive, ref, watch, onMounted, nextTick } from "vue";
import { ReturnTree } from "@whjxtech/jxtech-component";
import UserListSelect from "./user-list-select.vue";
import UnitTreeCard from "@/views/org/unit/component/unit-tree-card.vue";
import { ElMessage } from "element-plus";

const UserListRef = ref();
const emit = defineEmits<{
  (e: "update:visible", val: boolean): void;
  (e: "ok", val: any[]): void;
}>();

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  unitId: {
    type: String,
    default: ""
  }
});
const visibleModelValue = ref(props.visible);
watch(
  () => props.visible,
  val => {
    visibleModelValue.value = val;
  }
);
watch(visibleModelValue, val => {
  emit("update:visible", val);
  if (val) {
    nextTick(() => {
      UserListRef.value.getUserListTableRef().loadTable();
    });
  }
});

const UserListDialogState = reactive({
  queryParam: { unitId: "10000" },
  loadUserTable: () => {
    UserListRef.value.getUserListTableRef().loadTable();
  },
  handleClose: () => {
    visibleModelValue.value = false;
  },
  onSaveButtonClick: () => {
    const pkList = UserListRef.value.selectionListData();
    if (pkList.length > 0) {
      pkList.map((e: any) => {
        e.unitId = props.unitId;
        return e;
      });
      emit("ok", pkList);
    } else {
      ElMessage({
        type: "warning",
        message: "至少选中一项"
      });
    }
  },
  /**节点点击事件 */
  handleNodeClick: (treeData: ReturnTree<any>) => {
    UserListDialogState.queryParam.unitId = treeData.id;
    nextTick(() => UserListDialogState.loadUserTable());
  }
});
</script>
<template>
  <div class="jxtech-dialog-form">
    <slot></slot>
    <el-dialog
      class="user-list-select-dialog"
      v-model="visibleModelValue"
      title="选择用户"
      fullscreen
      destroy-on-close
      :before-close="UserListDialogState.handleClose"
    >
      <el-row :gutter="12">
        <el-col :span="6">
          <unit-tree-card @node-click="UserListDialogState.handleNodeClick"></unit-tree-card>
        </el-col>
        <el-col :span="18">
          <user-list-select ref="UserListRef" :query-param="UserListDialogState.queryParam"> </user-list-select>
        </el-col>
      </el-row>
      <template #footer>
        <span class="dialog-footer">
          <jxtech-cancel-button @click="UserListDialogState.handleClose"></jxtech-cancel-button>
          <jxtech-ok-button @click="UserListDialogState.onSaveButtonClick"></jxtech-ok-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped></style>
